subroutine metropolis
use para
implicit none
double precision,external::m1deltae,m2deltae,udeltae!,new_energy
double precision,external::ran1
double precision::linkde1,linkde2,tde,rate!,newe,sp1  !linkde1,linkde2
integer::slatt,slattm
integer::ulatt,uspin
integer::lattx,latty
integer::t

do lattx=1,nlatt
   do latty=1,natom
           if(sadap==1)scount=scount+1
           slatt=lattx
           slattm=latty
      

           tde = m1deltae(slatt,slattm)
if (tde<0.0.or.exp(-tde*beta(mybeta_num))>ran1(seed1))then


           if(sadap==1)sacpt=sacpt+1


           call delta_mag(slatt,slattm)

           tote=tote+tde

           call renewm(slatt,slattm)


end if


!control the spin adaptively
	    if(sadap==1.and.scount==slen)then
            probs=(1.0*sacpt)/scount

            if(probs>psmax)sdelta=sdelta*(1.0+beta0*(probs-psmax)/(1.0-psmax))
            if(probs<psmin)sdelta=sdelta/(1.0+beta1*(psmin-probs)/psmin)
            if(sdelta>1.0e6)sdelta=1.0e6
	     scount=0
	     sacpt=0
            end if

   
   end do
end do

end subroutine
